package inabit.crisp.inference;

import inabit.base.WorkingMemory;
import inabit.data.FireableRule;
import inabit.data.Rule;
import inabit.data.expression.ConsequentExpression;
import inabit.data.expression.Expression;
import inabit.inference.BackwardEngine;
import inabit.inference.InferenceNode;

import java.util.List;
import java.util.Scanner;

import javax.swing.tree.DefaultTreeModel;
/**A implementation of the backward engine
 * @author Rafael Rocha*/
public class BackwardEngineImpl extends BackwardEngine {
	private Scanner scanner;

	public BackwardEngineImpl() {
		this.scanner = new Scanner(System.in);
	}

	@Override
	protected FireableRule resolveSet(
			List<FireableRule> conflictSet) {
		return conflictSet.get(conflictSet.size() - 1);
	}

	@Override
	protected Double ask(Expression exp, Rule r, WorkingMemory wm) {
		System.out.println(exp.toString() + "?");
		String user = scanner.next();
		while (true) {
			DefaultTreeModel trace = getTraceTreeModel();
			int i = 1;
			/*
			while (user.equals("why")) {
				for (int j = 0; j < i; j++) {
					Rule rule = trace.get(j);
					System.out.println(rule);
				} 

				if (i < trace.size()) {
					Rule rule = trace.get(i - 1);
					System.out.println("And i if I know if " + exp
							+ " than I will know if " + rule.getPrecedent());
					i++;
				}
				user = scanner.next();
			}*/

			if (user.equals("yes")) {
				return 1.0;
			} else if (user.equals("no")) {
				return 0.0;
			} else if(user.equals("dunno")){
				return null;
			}else {
				System.out.println("Please write yes, no or dunno");
				System.out.println(exp.toString() + "?");
				user = scanner.next();
			}	
		}
	}

	@Override
	protected String getInnerNodeLabel(Rule r) {
		return r.getPrecedent().stringForm();
	}

	@Override
	protected String getRootNodeLabel(String goal) {
		return goal + "?";
	}

	@Override
	protected String getGoalNodeLabel(Expression exp) {
		return exp.stringForm();
	}
}
